#ifndef SERVERCONNECTION_H
#define SERVERCONNECTION_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
#include <QByteArray>
#include <QMap>
#include <QtNetwork>
#include "Delimetrs.h"


class ServerConnection : public QObject
{
    Q_OBJECT
public:
    explicit ServerConnection(QObject *parent = 0);
    ~ServerConnection();
    const QString getIP();
    void setPort(int _port);
    void run();
    void stop();
    void sendToClient(QTcpSocket* pClientSocket,const QString str);
    void sendToClient(int localId, const QString str);
    void sendToPlayer(int playerId, const QString str);
    void sendToAllPlayers(const QString str);
    void sendToAllSockets(const QString str);

    //function which ServerMessageManager is calling
    //  when receives signal GAME_START
    //  functions calls stopNewConnections() and breakNotPlayerConnections()
    void gameStarts();
    void stopNewConnections();
    void breakNotPlayerConnections();
    //adds TcpSocket to TcpPlayers
    void addPlayer(int localId, int playerId);
signals:
    void signalConnectionError();
    void signalReceivedFromClient(int localID, QString str);
    void signalReceivedFromPlayer(int playerId, QString str);
    void signalPlayerDisconnected(int playerId);
    void signalClientDisconnected(int localId);

public slots:
    //slot for catching new connection
    //  sets newTcpSocket objectName = FreeClientId++
    //  adds (objName, *newTcpSocket) to TcpClients
    //  creates (objName, QString Buffer="") to ClientsBuffer
    void slotNewConnection();
    //catcher of SIGNAL(readyRead())
    //  new bytes are pushed into ClientsBuffer[localI]
    //  if buffer contains complite message it
    //  emits signalReceivedFromClient(int localID, QString str)
    //  or void signalReceivedFromPlayer(int playerId, QString str);
    void slotReadClient();
    //deletes all temporary data about client and disconnects him
    void slotDeleteFromTcpClient();

private:
    int FreeClientId;   //used for localId, at start = 1;
    QMap<int, QTcpSocket*> TcpClients;//key = TcpSocket local id
    QMap<int, QTcpSocket*> TcpPlayers;//key = Game playersId
    QMap<int, int> LocalIdToTankId;  //key = TcpSocket local id
    QMap<int, QString> ClientsBuffer;//key = TcpSocket local id
    QTcpServer *ptcpServer;
    int Port;

};

#endif // SERVERCONNECTION_H
